package com.qingfeng.medical.biz.auth.mq.consumer;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingfeng.medical.base.utils.MD5;
import com.qingfeng.medical.biz.auth.dao.SysRoleMapper;
import com.qingfeng.medical.biz.auth.dao.SysUserMapper;
import com.qingfeng.medical.biz.auth.dao.SysUserRoleMapper;
import com.qingfeng.medical.biz.auth.domain.entity.SysRole;
import com.qingfeng.medical.biz.auth.domain.entity.SysUser;
import com.qingfeng.medical.biz.auth.domain.entity.SysUserRole;
import com.qingfeng.medical.biz.auth.domain.enums.RoleEnums;
import com.qingfeng.medical.biz.auth.domain.excel.SysUserExcelVo;
import com.qingfeng.medical.config.mq.RabbitMqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 清风学Java
 * @version 1.0.0
 * @date 2022/12/19
 */
@Component
public class RabbitReceiveUserHandler {

    private static Integer COUNT = 0;
    private static Integer MAX_LIMIT = 3;


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;


    /**
     * 监听邮箱队列的消费
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitMqConfig.QUEUE_USER_INFO})
    public void send_email(Message message, Channel channel) throws IOException {
        // 采用手动应答模式, 手动确认应答更为安全稳定
        if (COUNT.equals(MAX_LIMIT)) {
            COUNT = 0;
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }

        // 接收到对象
        SysUserExcelVo sysUserExcelVo = objectMapper.readValue(
                new String(
                        message.getBody(),
                        StandardCharsets.UTF_8
                ),
                SysUserExcelVo.class);

        // 判断用户对象是否重复  用户名不能重复
        List<SysUser> sysUsers = sysUserMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, sysUserExcelVo.getUsername())
        );
        if (CollUtil.isNotEmpty(sysUsers)) {
            // TODO 将重复的用户信息记录下来

        }

        //添加用户 到这一步的已经是去重的用户
        SysUser sysUser = SysUser.builder()
                .username(sysUserExcelVo.getUsername())
                .password(MD5.encrypt(sysUserExcelVo.getPassword()))
                .phone(sysUserExcelVo.getPhone())
                .name(sysUserExcelVo.getName())
                .status(1)
                .build();
        sysUserMapper.insert(sysUser);

        // 分配角色，都是普通医师
        sysUserRoleMapper.insert(SysUserRole.builder()
                .roleId(sysRoleMapper.selectOne(
                                new LambdaQueryWrapper<SysRole>()
                                        .eq(SysRole::getRoleCode, RoleEnums.GENERAL_PHYSICIAN.name())
                        ).getId()
                )
                .userId(sysUser.getId())
                .build());


        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

    /**
     * 监听死信队列的消费
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitMqConfig.DEAD_LETTER_QUEUE})
    public void dead_email(Message message, Channel channel) throws IOException {
        // TODO 一旦进入死信队列，需要给用户发送消息，并且将失败的信息保存起来，以便后面恢复

        // 采用手动应答模式, 手动确认应答更为安全稳定
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

}
